package com.github.pig.nideshop.weixin.handler;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pig.nideshop.entity.NideshopUser;
import com.github.pig.nideshop.service.INideshopUserService;
import com.github.pig.nideshop.weixin.builder.TextBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class SubscribeHandler extends AbstractHandler {
  @Autowired
  private INideshopUserService nideshopUserService;
  @Override
  @Transactional
  public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context, WxMpService weixinService,
                                  WxSessionManager sessionManager) throws WxErrorException {

    this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());

    // 获取微信用户基本信息
    WxMpUser userWxInfo = weixinService.getUserService()
        .userInfo(wxMessage.getFromUser(), null);

    if (userWxInfo != null) {
      NideshopUser user=new NideshopUser();
      user.setAvatar(userWxInfo.getHeadImgUrl());
      user.setGender(userWxInfo.getSex());
      user.setNickname(userWxInfo.getNickname());
      user.setWeixinOpenid(userWxInfo.getOpenId());
      user.setUsername(userWxInfo.getNickname());
      user.setRegisterTime(System.currentTimeMillis()/1000);
      user.setLastLoginTime(System.currentTimeMillis()/1000);
      user.setSubscribe(1);
      EntityWrapper<NideshopUser> entityWrapper=new EntityWrapper<>();
      entityWrapper.eq("weixin_openid",userWxInfo.getOpenId());
      NideshopUser nideshopUser=nideshopUserService.selectOne(entityWrapper);
      if(nideshopUser!=null){
        user.setId(nideshopUser.getId());
        user.setUsername(nideshopUser.getUsername());
      }
      log.info("用户关注处理结果:{}",nideshopUserService.insertOrUpdate(user));
    }

    WxMpXmlOutMessage responseResult = null;
    try {
      responseResult = handleSpecial(wxMessage);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    if (responseResult != null) {
      return responseResult;
    }

    try {
      return new TextBuilder().build("感谢关注", wxMessage, weixinService);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    return null;
  }

  /**
   * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
   */
  private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
      throws Exception {
    //TODO
    return null;
  }

}
